package cn.frank.framework.king.conf.aspect.async;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


/**
 * 自定义异步执行注解切面
 *
 * @author renjy
 * @since 2023/3/20 16:03:37
 */
@Component
@Aspect
@Slf4j
public class UserTaskAspect {

    public static ThreadLocal<String> taskIdThreadLocal = new ThreadLocal<>();

    @Pointcut("@annotation(cn.frank.framework.king.conf.aspect.async.UserTaskAnnotation)")
    public void annotationPoint() {
    }


    /**
     * 其中@Around定义满足切点annotationPoint()
     *
     * @return 实际请求方法回参
     */
    @Around(value = "annotationPoint() && @annotation(userTaskAnnotation)", argNames = "proceedingJoinPoint,userTaskAnnotation")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, UserTaskAnnotation userTaskAnnotation) {
        new Thread(() -> {
            try {
                Object result = proceedingJoinPoint.proceed();
                log.info("结果 result={}", JSONUtil.toJsonStr(result));
            } catch (Exception e) {
                log.error("用户userId={} 运行任务taskName={} 执行异常", e);
                throw new RuntimeException(e);
            } catch (Throwable e) {
                log.error("用户userId={} 运行任务taskName={} 执行异常", e);
                throw new RuntimeException(e);
            } finally {
                taskIdThreadLocal.remove();
            }
        }).start();
        return null;
    }


}
